package com.bmf.core.result;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class WebUtils {
    private WebUtils() {
        throw new IllegalStateException("Utility class");
    }


    public static void renderString( int code,String msg) {
        renderString(R.failed(code, msg));
    }

    public static void renderString( R<Object> result) {
        try {
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.reset();
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "*");
            response.setHeader("Access-Control-Request-Headers", "*");
            response.setStatus(HttpStatus.OK.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            String r = JSONUtil.toJsonStr(result);
            response.getWriter().print(r);
        } catch (IOException e) {
            log.error(ExceptionUtil.stacktraceToString(e));
        }
    }
}